package com.danton.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.danton.common.bean.Constants;
import com.danton.common.exception.UserAlreadyExistException;
import com.danton.model.BsAdminModel;
import com.danton.model.BsAdminRoleModel;
import com.danton.model.BsPermissionModel;
import com.danton.model.BsRoleModel;
import com.danton.user.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

public class UserServiceImpl implements UserService {
	protected static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	/**
	 * 通过用户名查询用户
	 * 
	 * @param userName
	 * @return
	 */
	public BsAdminModel findByUserName(String user_name) {
		return BsAdminModel.dao.findByUserName(user_name);
	}

	/**
	 * 通过用户名密码查询用户
	 * 
	 * @param userName
	 * @param password
	 * @return
	 */
	public BsAdminModel findByUserNameAndPassword(String user_name, String password) {
		return BsAdminModel.dao.findByUserNameAndPassword(user_name, password);
	}

	/**
	 * 通过用户ID查询角色列表
	 * 
	 * @param userID
	 * @return
	 */
	public List<BsRoleModel> findRolesByUserID(int user_id) {
		return BsRoleModel.dao.findRolesByUserID(user_id);
	}
	
	/**
	 * 通过用户ID查询角色列表,只返回bs_role表
	 * 
	 * @param userID
	 * @return
	 */
	public List<BsRoleModel> findRoleNameByUserID(int user_id) {
		return BsRoleModel.dao.findRoleNameByUserID(user_id);
	}

	@Override
	public List<BsRoleModel> findRolesByUserName(String user_name) {
		int user_id = BsAdminModel.dao.findByUserName(user_name).getInt("id");
		return BsRoleModel.dao.findRolesByUserID(user_id);
	}

	/**
	 * 通过用户ID查询权限列表
	 * 
	 * @param userID
	 * @return
	 */
	public List<BsPermissionModel> findPermissionsByUserID(int user_id) {
		List<BsRoleModel> roles = BsRoleModel.dao.findRolesByUserID(user_id);
		if (roles.size() == 0) {
			return new ArrayList<BsPermissionModel>();
		}
		List<Integer> idList = new ArrayList<Integer>();
		for (BsRoleModel bsRoleModel : roles) {
			idList.add(bsRoleModel.getInt("id"));
		}
		return BsPermissionModel.dao.findPermissionsByRoleIDs(idList);
	}

	/**
	 * 注册用户
	 * 
	 * @param user_name
	 * @param password
	 * @throws UserAlreadyExistException
	 *             用户已经存在
	 */
	@Before(Tx.class)
	public boolean register(BsAdminModel adminModel, String role_code, String access_key_id)
			throws UserAlreadyExistException {
		String user_name = adminModel.getStr("user_name");
		String password = adminModel.getStr("password");
		String ip_address = adminModel.getStr("ip_address");
		BsAdminModel baModel = BsAdminModel.dao.findByUserName(user_name);

		boolean addResult = false;
		if (baModel != null) {
			throw new UserAlreadyExistException();
		} else {
			// 加密密码,用ip做盐
			password = new Sha1Hash(password, ip_address).toString();
			logger.debug("sha1:" + password);
			addResult = adminModel.set("password", password).save();
			if (addResult && role_code != null) {
				int admin_id = adminModel.getInt("id");
				BsRoleModel roleModel = BsRoleModel.dao.findRoleByRoleCode(role_code);
				if (roleModel != null) {
					int role_id = roleModel.getInt("id");
					BsAdminRoleModel arModel = new BsAdminRoleModel();
					arModel.set("admin_id", admin_id).set("role_id", role_id).save();
				}
			}
		}
		return addResult;
	}

	@Override
	public boolean checkLoginPermission(String user_name, String access_key_id) {
		BsAdminModel adminModel = BsAdminModel.dao.findByUserName(user_name);
		if (adminModel == null) {
			return false;
		}
		Integer user_id = adminModel.getInt("id");
		List<BsPermissionModel> permissionList = findPermissionsByUserID(user_id);
		for (BsPermissionModel bsPermissionModel : permissionList) {
			String resource = bsPermissionModel.get("resource");
			String[] str = resource.split(":");
			if (str[0].equals(Constants.PERMISSION_LOGIN) && str[1].equals(access_key_id)) {// 是否有登陆权限
				return true;
			}
		}
		return false;
	}

	@Override
	public Page<BsAdminModel> listUser(int pn, int ps) {
		return BsAdminModel.dao.paginate(pn, ps);
	}

	@Override
	public Page<BsAdminModel> searchUser(int pn, int ps, String kw) {
		return BsAdminModel.dao.paginateByKw(pn, ps, kw);
	}

	@Override
	public boolean edit(BsAdminModel adminModel) {
		String user_name = String.valueOf(adminModel.get("user_name"));
		BsAdminModel am = findByUserName(user_name);
		if (am == null) {//修改后不存在此用户，可以修改
			return adminModel.update();
		}
		return false;
	}

	@Override
	public BsAdminModel findByUserID(int id) {
		return BsAdminModel.dao.findById(id);
	}

	@Override
	public void resetPassword(int user_id) {
		BsAdminModel adminModel = BsAdminModel.dao.findById(user_id);
		String identity_code = adminModel.getStr("identity_code");
		String password = identity_code.substring(identity_code.length()-6);// TODOHouliuwei
		System.out.println(password);
		String ip_address = adminModel.getStr("ip_address");
		password = new Md5Hash(password).toString();
		// 加密密码,用ip做盐
		password = new Sha1Hash(password, ip_address).toString();
		logger.debug("sha1:" + password);
		adminModel.set("password", password).update();
	}

	@Override
	public List<BsAdminModel> findUserByRoleID(int role_id) {
		return BsAdminModel.dao.findUserByRoleID(role_id);
	}

	@Override
	public boolean deleteUser(int role_id) {
		String sql = "select * from bs_admin_role where role_id=" + "'" + role_id + "'";
		List<BsAdminRoleModel> list = BsAdminRoleModel.dao.find(sql);
		if (list != null) {
			for (BsAdminRoleModel rpm : list) {
				boolean ffalg = rpm.delete();
				if (!ffalg)
					return false;
			}
		}
		return true;
	}

	@Override
	public int AddAdminRole(List<BsAdminRoleModel> list) {
		for (BsAdminRoleModel arm : list) {
			boolean flag = arm.save();
			if (!flag) {
				return 1;
			}
		}
		return 0;
	}

	@Override
	public boolean UpdateAdmin(BsAdminModel admin) {
		return admin.update();
	}


	@Override
	public boolean updatePassword(int user_id, String newpassword) {
		return false;
	}

}
